import axios from "axios";
import {ElMessage} from "element-plus";

const server = axios.create({
    baseURL: "http://localhost:8080",
    timeout: 5000,
})


server.interceptors.request.use(config => {
    // 改为从 sessionStorage 获取
    let token = sessionStorage.getItem("token");
    // console.log('请求拦截器 - Token:', token);

    if (token) {
        config.headers['token'] = token;
        // console.log('已设置token头');
    }

    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器也要相应修改
server.interceptors.response.use(resp => {
    // console.log('响应拦截器:', resp);

    if (resp.data.code === 401 || resp.data.code === 407) {
        ElMessage.error("登录过期,请先登录");
        sessionStorage.removeItem('token');  // 改为sessionStorage
        window.location.href = '/login';
    }

    return resp;
}, error => {
    if (error.response?.status === 401) {
        ElMessage.error("登录已过期，请重新登录");
        sessionStorage.removeItem('token');  // 改为sessionStorage
        window.location.href = '/login';
    }
    return Promise.reject(error);
});
export default server
